package com.xianniu.ltc.aspect;

import cn.devezhao.persist4j.Query;
import cn.devezhao.persist4j.Record;
import cn.devezhao.persist4j.engine.ID;
import com.rebuild.core.Application;
import com.rebuild.core.BootEnvironmentPostProcessor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author dingyuxin
 *
 */
@Slf4j
@Aspect
@Component
public class SaveInternalAspect {

    //拦截指定的方法,这里指只拦截TestService.getResultData这个方法
    @Pointcut("execution(public * com.rebuild.core.service.CommonsService.create(..)) || " +
            "execution(public * com.rebuild.core.metadata.impl.MetaEntityService.update(..))")
    public void excuteService() {

    }

    //执行方法前的拦截方法
    @Before("excuteService()")
    public void doBeforeMethod(JoinPoint joinPoint) {
        log.info("前置通知，如果是meta_field表，修改查询insert into 的tenantCode参数为默认租户");
        //获取目标方法的参数信息
        Object[] obj = joinPoint.getArgs();
        for (Object o : obj) {
            System.out.println("---->now-->argItem:" + o);
            if (o instanceof Record) {
                Record record = (Record) o;
                if (record.getEntity().getPhysicalName().equalsIgnoreCase("meta_field") ||
                        record.getEntity().getPhysicalName().equalsIgnoreCase("meta_entity")){
//                    Object object = checkIsExist(record);
//                    if (((Long) object).intValue() == 0){
//                        record.setString("tenantCode", BootEnvironmentPostProcessor.getDefaultTenant());
//                    }
                    record.setString("tenantCode", BootEnvironmentPostProcessor.getDefaultTenant());
                }
            }
        }
    }

    /**
     * 校验字段是否已保存，避免二次保存（暂不使用）
     * @param record
     * @return
     */
    public Object checkIsExist(Record record){
        String sql = String.format("select count(fieldId) from metaField where belongEntity = ? and fieldName = ? and tenantCode = ? ");
        Query kehushu = Application.createQueryNoFilter(sql)
                .setParameter(1, record.getString("belongEntity"))
                .setParameter(2, record.getString("fieldName"))
                .setParameter(3, BootEnvironmentPostProcessor.getDefaultTenant());

        Object[] result = kehushu.unique();
        Object obj = Objects.isNull(result[0]) ? 0:result[0];
        return obj;
    }
}